import { createApp } from './app'

const { app, router, store } = createApp()

if (window.__INITIAL_STATE__) {
  store.replaceState(window.__INITIAL_STATE__)
}

router.onReady(() => {
  router.beforeResolve((to, from, next) => {
    const matchedComponents = router.getMatchedComponents(to)
    const prevMatchedComponents = router.getMatchedComponents(from)
    let diffed = false
    const activated = matchedComponents.filter((item, index) => {
      return diffed || (diffed = prevMatchedComponents[index] !== item)
    })
    if (!activated.length) {
      next()
    }

    Promise.all(activated.map(item => {
      if (item.asyncData) {
        return item.asyncData({ store, route: to })
      }
    })).then(() => {
      next()
    }).catch(next)
  })

  app.$mount('#app')
})
